﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Sgr.BackGroundTasks;
using Sgr.Modules;
using Sgr.Security.Permissions;
using Sgr.Workspace.BackGroundTasks;
using Sgr.Workspace.Services;
using Sgr.Workspace.Services.Impl;

namespace Sgr.Workspace
{
    public class ModuleStartup : ModuleStartupBase
    {
        public const string AppOperationSummaryBackgroundTaskId = "AppOperationSummaryBackgroundTask";

        public override int Order => 100;

        public override void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            var config = app.ApplicationServices.GetRequiredService<IConfiguration>();
            bool runOnce = config.GetValue<bool>("Sgr:Workspace:RunSummaryOnceOnStartup");

            if (runOnce)
            {
                var scopeFactory = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>();
                _ = Task.Run(async () =>
                {
                    using var scope = scopeFactory.CreateScope();
                    var task = scope.ServiceProvider.GetRequiredService<AppOperationSummaryBackgroundTask>();
                    var logger = scope.ServiceProvider.GetService<ILogger<AppOperationSummaryBackgroundTask>>();
                    try
                    {
                        await task.ExecuteAsync();
                    }
                    catch (Exception ex)
                    {
                        logger?.LogError(ex, "启动时执行 AppOperationSummaryBackgroundTask 失败");
                    }
                });
            }
        }

        public override void ConfigureServices(IServiceCollection services)
        {
            services.TryAddEnumerable(ServiceDescriptor.Singleton<IPermissionProvider, Permissions>());

            services.AddScoped<IAppAnalysisService, AppAnalysisService>();

            // 注册审计日志背景任务
            services.AddBackGroundTask<AppOperationSummaryBackgroundTask>();

            var config = services.GetConfiguration();
            string cron = config.GetValue<string>("Sgr:BackGroundTasks:Cron:AppOperationSummaryBackgroundTask") ?? "0 0 3 * * ?"; // 每天夜间3点执行一次

            services.Configure<BackGroundTaskOptions>(opts =>
            {
                opts.RegistRecurringTask<AppOperationSummaryBackgroundTask>(
                    AppOperationSummaryBackgroundTaskId,
                    "系统运营情况汇总后台任务",
                    cron
                );
            });
        }
    }
}